/**
 * 
 */
package com.dosgi.kit;

import java.io.File;
import java.io.IOException;

/**
 * 路径工具类
 * @author dingnate
 */
public class PathKit {
	private static String webRootPath;
	private static String rootClassPath;

	public static String getRootClassPath() {
		if (rootClassPath != null){
			return rootClassPath;
		}
		rootClassPath = new File(PathKit.class.getClassLoader().getResource("").getPath()).getAbsolutePath();
		return rootClassPath;
	}

	public static String getWebRootPath() {
		if (webRootPath == null){
			webRootPath = detectWebRootPath();
		}
		return webRootPath;
	}

	public static boolean isAbsolutelyPath(String path) {
		return path.startsWith("/") || path.indexOf(':') == 1;
	}

	public static String getParent(String path) {
		int i = path.length() - 1;
		//去除尾部的分隔符
		while (i >= 0 && ('/' == path.charAt(i) || '\\' == path.charAt(i))){
			i--;
		}
		//找到父子分隔符
		while (i >= 0) {
			if ('/' == path.charAt(i) || '\\' == path.charAt(i)){
				break;
			}
			i--;
		}
		//去除父尾部的分隔符
		while (i >= 0 && ('/' == path.charAt(i) || '\\' == path.charAt(i))){
			i--;
		}
		return path.substring(0, i + 1);
	}

	public static String append(String parent, String child) {
		int i = parent.length() - 1;
		//去除父尾部的分隔符
		while (i >= 0 && (parent.charAt(i) == '/' || parent.charAt(i) == '\\')){
			i--;
		}
		boolean bool = false;
		if (i < parent.length() - 1) {
			//使用父尾部的分隔符
			i++;
			bool = true;
		}
		int j = 0;
		//去除子头部的分隔符
		while (j < child.length() && (child.charAt(j) == '/' || child.charAt(j) == '\\')){
			j++;
		}
		if (!bool){
			if (j > 0) {
				//使用子头部的分隔符
				--j;
				bool = true;
			}
		}
		StringBuilder b = new StringBuilder(parent.substring(0, i + 1));
		//父子之间没有分隔符，则添加分隔符
		if (!bool){
			b.append("/");
		}
		return b.append(child.substring(j)).toString();
	}

	private static String detectWebRootPath() {
		try {
			String path = PathKit.class.getResource("/").toURI().getPath();
			return new File(path).getParentFile().getParentFile().getCanonicalPath();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 获取 绝对路径
	 * @param path
	 * @return
	 */
	public static String resolvePath(String path) {
		if (isAbsolutelyPath(path)) {
			return path;
		}
		try {
			return new File(path).getCanonicalPath();
		} catch (IOException e) {
			return path;
		}
	}
}
